################################################################################################

cluster=$1
config_path=$2

source ${config_path}/config.sh

# cluster=cluster0
clustern=`echo $cluster | awk -F"cluster" '{print $2}'`
echo "cluster${clustern} start"

################################################################################################
## 输出文件夹

output_dir=${work_dir}/results/cluster_all_result
peak_dir=${output_dir}/cluster${clustern}/consensus
frag_dir=${output_dir}/cell_fragment

mkdir -p ${peak_dir}
mkdir -p ${frag_dir}
mkdir -p ${output_dir}/cluster${clustern}/count
mkdir -p ${output_dir}/cluster${clustern}/fragment
mkdir -p ${output_dir}/cluster${clustern}/annotation

################################################################################################
## 提取细胞特异的peak
cat ${work_dir}/results/atac_res/testis_combined_peak.tsv | \
awk -F'\t' '{OFS="\t"}{if($19==clustern)print}' clustern=${clustern}| \
awk -F'\t' '{OFS="\t"}{print $1,$2,$3,cluster"_"NR,$6,$5}' cluster=${cluster} > \
${peak_dir}/cluster${clustern}.fwp.filter.non_overlapping.bed

#bgzip ${peak_dir}/cluster${clustern}.fwp.filter.non_overlapping.bed

################################################################################################
## 和ATAC的文件取交集
${bedtools} intersect \
-a ${peak_dir}/cluster${clustern}.fwp.filter.non_overlapping.bed \
-b ${input_dir}/testis01_atac_fragments.tsv.gz -wa -wb \
> ${output_dir}/cluster${clustern}/fragment/cluster${clustern}_testis01_frag_overlap.txt

${bedtools} intersect \
-a ${peak_dir}/cluster${clustern}.fwp.filter.non_overlapping.bed \
-b ${input_dir}/testis02_atac_fragments.tsv.gz -wa -wb \
> ${output_dir}/cluster${clustern}/fragment/cluster${clustern}_testis02_frag_overlap.txt

${bedtools} intersect \
-a ${peak_dir}/cluster${clustern}.fwp.filter.non_overlapping.bed \
-b ${input_dir}/testis03_atac_fragments.tsv.gz -wa -wb \
> ${output_dir}/cluster${clustern}/fragment/cluster${clustern}_testis03_frag_overlap.txt

echo "cluster${clustern} fragments finished"

################################################################################################
## 三个文件分别取
batch_list=(1 2 3)

for batch in ${batch_list[@]}
do
echo $batch

${Rscript_archr} ${scripts_dir}/cluster_batch_count.R \
 --cluster ${clustern} \
 --batch ${batch} \
 --barcode ${frag_dir} \
 --peak ${peak_dir}/cluster${clustern}.fwp.filter.non_overlapping.bed \
 --frag ${output_dir}/cluster${clustern}/fragment \
 --output ${output_dir}/cluster${clustern}/count
echo "cluster${clustern} testis${batch} count finished"

done

echo "cluster${clustern} count finished"

# END! #
echo "cluster${clustern} finished"

################################################################################################
## 注释文件
${bedtools} intersect \
-a ${peak_dir}/cluster${clustern}.fwp.filter.non_overlapping.bed \
-b ${ref_path}/GTF/gencode_v32_prom_enhan.bed \
-wo > ${output_dir}/cluster${clustern}/annotation/cluster${clustern}_peak_annoatation.txt